<script>
import cache from "./utils/cache";
import  {getAuthToken} from "./utils/index";

export default {
  //当uni-app初始化完成时触发(全局只触发一次)

  onLaunch: function (e) {
    let type = e.query.type;
    console.log('app-type--->' + type);
    //全局緩存用戶
    console.log('App Launch 全局只触发一次')

    this.initData(type)
    //执行完onLaunch后再执行页面onLoad
    setTimeout(() => {
      console.log('倒计时结束');
      this.$isResolve()
    },2000);
  },
  //当uni-app启动，或从后台进入前台显示
  onShow: function() {
    console.log('App Show')
  },
  //当uni-app从前台进入后台
  onHide: function() {
    console.log('App Hide')
  },
  // 全局变量
  globalData: {
    appId:'',
    appType:''
  },

  //封装的函数
  methods:{
    //初始化数据
    async initData(type) {
//      await getAuthToken()
      // 加载app配置信息
//      await this.getAppInfoAll()
//      await this.getAppId(type)
      await this.cacheUserInfo()
      await this.getDicByDictCodes('bgqx,reviewType,mj,jjcd,dbjjcd,infopublic,fileAttribute,isSupervise,isPolicy,' +
              'isInterpret,isLegal,gxfl,xzsplgw,source,content,swjjcd,gljswjjcd,gwfdjjcd,swLanguage,fileType,limitDays')
      await this.loadOrgTree() //加载单位树
      await this.getDic('limitDays')

    },
    // 获取所有app配置信息
    async getAppInfoAll() {
      await this.$http({
        url: this.$http.adornUrl(`/caac-admin/lx/api/getAppInfoAll`),
        method: 'get',
      }).then(({data}) => {
        if (data.code == 200) {
          console.log('全部应用信息--->' + JSON.stringify(data.appInfo));
          this.cache.set('appInfo', data.appInfo)
        }
      });
    },
    // 获取app信息
    getAppId(type) {
      if(this.util.isEmpty(type)) {
        type='search';
      }
      let appInfos = this.cache.get('appInfo');
      if (appInfos == null || appInfos.length == 0) {
        this.$toast('获取app配置信息失败，请稍后再试！')
      }
      let appIds = appInfos.filter(item => item.type == type)
      if (appIds != null && appIds.length > 0) {
        this.globalData.appId = appIds[0].appId
        this.globalData.appType = appIds[0].type
      }
      this.cache.set("appId", this.globalData.appId );
      this.cache.set("appType", this.globalData.appType);
      console.log('app-appId--->' + this.cache.get("appId"));
      console.log('app-appType--->' + this.cache.get("appType"));
      console.log('app-globalData:'+JSON.stringify(this.globalData))
    },
//緩存全局用戶
    async cacheUserInfo(){
      // 正式
//       await this.lx.getUserInfo(this.cache.get("appId") , this.cache.get("appType"))
//       let lxUserInfo = this.cache.get('lxUserInfo')
//       let userName = lxUserInfo.loginName
//       userName = userName.split('@')[1]
////       let userInfo = {
////         systemKey: userName,
////         systemFlag: 'yidong'
////       }
//       console.log("App.vue获取蓝信用户信息:"+JSON.stringify(lxUserInfo))
      // 测试
      let userInfo={
        systemKey: 'sm_liu', // yinchengwei_hb lipan_hb xintianhe_hb jb_sun ls_liu zhangqi xm_ge jb_sun liuzhigang_hb
        systemFlag: 'yidong'
      }
      await this.getUserInfoByUserCode(userInfo)
    },
    /**
     * 通过用户userCode{lipan_hb}获取用户信息接口
     * @param {Object} userCode
     */
    async getUserInfoByUserCode(userInfo){
      await this.$http({
        url: this.$http.adornUrl(`/caac/oa/app/queryMainDept`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': userInfo.systemKey,
          'systemFlag': userInfo.systemFlag
        })
      }).then(({data}) => {
        // data: {"code":200,"data":{"deptName":"华北管理局","zipCode":"1     ","allParentId":"0,002,002001","extend10":null,"leaderId":"sysadmin","divisionId":"--","address":"1","deptLevel":1,"isValid":"1","deptId":"002001","updateUser":null,"telephone":"11","updateTime":null,"deptType":"org","sort":36,"userId":"5741","parentId":"002","extend7":null,"extend6":"002001","extend9":null,"depth":null,"extend8":null,"extend3":null,"createTime":"2021-07-27T12:30:00.011+0000","extend2":null,"extend5":null,"extend4":null,"createUser":"CAAC_SYSTEM","extend1":"华北管理局","deptCode":"002001"},"message":null}
        // console.log("data: " + JSON.stringify(data));
        if(data.code == 200){
          this.$set(data.data,'systemKey',userInfo.systemKey)
          this.$set(data.data,'systemFlag',userInfo.systemFlag)
          this.cache.set('userInfo',data.data)
        }
        console.log("用户信息-->data: " + JSON.stringify(data));
      })
    },
    /**
     *  dictCodes=reviewType 多个用,分割
     *  reviewType 意见类型
     *  mj 密级
     *  jjcd 紧急程度
     *  infopublic 公开类型
     *  fileAttribute 文件属性
     *  isSupervise 是否为督查反馈公文
     *  isPolicy 是否为重要政策性文件
     *  isInterpret 是否有解决方案
     *  isLegal 是否有文件合法性审查结果
     *  gxfl 个性分类
     */
    getDicByDictCodes(dictCodes){
      var result
      var _this = this
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/comm/dict/dicts`),
        method: 'get',
        params: this.$http.adornParams({
          'dictCodes': dictCodes,
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        if(data.code==200){
          if(dictCodes.indexOf(',')){
            var dic=dictCodes.split(',');
            for (var i = 0; i < dic.length; i++) {
              console.log("dic[i]: " + dic[i])
              this.cache.set(dic[i],data.data[dic[i]],false)
            }
          }

        }else{
          console.log('获取全局字典信息失败,code:'+data.code+',message:'+data.message);
        }
        if(data.code==500){
          console.log("获取字典出错"+data.message);
        }

      })
    },
    //获取字典值，测试用
    getDic(dictCodes){
      console.log("测试获取字典:---"+dictCodes+":" + JSON.stringify(this.cache.get(dictCodes)));
    },
    //加载呈报单位树
    loadOrgTree(){
      var _this = this
      this.$http({
        url: this.$http.adornUrl(`/caac/platform/org/depts/orgDeptTree`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag,//固定值
          'showNode':'002001'//只查管理局的树
        })
      }).then(({data}) => {
        // console.log("单位信息data: " + JSON.stringify(data.data));

        if(data.code==200){
          let orgTree = _this.treeDataTranslate(data.data,'deptId','parentId')
          // console.log("orgTree: " + JSON.stringify(orgTree));
          this.cache.set('orgTree',orgTree,false)
        }
      })
    },
    //将后台返回的list数组组装成树
    treeDataTranslate (data, id, pid) {
      var res = []
      var temp = {}
      for (var i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i]
      }
      for (var k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
          if (!temp[data[k][pid]]['children']) {
            temp[data[k][pid]]['children'] = []
          }
          if (!temp[data[k][pid]]['_level']) {
            temp[data[k][pid]]['_level'] = 1
          }
          data[k]['_level'] = temp[data[k][pid]]._level + 1
          temp[data[k][pid]]['children'].push(data[k])
        } else {
          res.push(data[k])
        }
      }
      return res
    }
  }

}
</script>

<style lang="scss">
@import "colorui/main.css";
@import "colorui/icon.css";
@import "uview-ui/index.scss";
@import "static/iconfont/iconfont.css";
/* 设置页面高度100% */
html, body{
  background-color: #FFFFFF;
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
}
.page {
  background-color: rgb(244, 240, 246);
  width: 100%;
  margin: 0 auto;
}

.van-cell__title {
  min-width: 70%;

  span {
    display: inline-block;
    text-align: left;
    word-break: break-all;
  }
}

</style>
